import { defineStore } from 'pinia';
import { store } from '@/store';
import { AccountInfo, CachedAccountInfo } from '@/types/account';
import { fetchAccountInfo } from '@/api/account';

// 缓存过期时间：10秒
const CACHE_DURATION = 10 * 1000;

export interface IAccountState {
  accountInfo: CachedAccountInfo | null;
  loading: boolean;
  error: string | null;
}

export const useAccountStore = defineStore({
  id: 'app-account',
  state: (): IAccountState => ({
    accountInfo: null,
    loading: false,
    error: null,
  }),
  getters: {
    getAccountInfo(): CachedAccountInfo | null {
      return this.accountInfo;
    },
    isLoading(): boolean {
      return this.loading;
    },
    getError(): string | null {
      return this.error;
    },
    // 检查缓存是否过期
    isCacheExpired(): boolean {
      if (!this.accountInfo) return true;
      return Date.now() > this.accountInfo.expires_at;
    },
    // 获取缓存剩余时间（秒）
    getCacheRemainingTime(): number {
      if (!this.accountInfo) return 0;
      const remaining = Math.max(0, this.accountInfo.expires_at - Date.now());
      return Math.ceil(remaining / 1000);
    },
  },
  actions: {
    // 设置账户信息并添加缓存时间戳
    setAccountInfo(accountInfo: AccountInfo) {
      const now = Date.now();
      this.accountInfo = {
        ...accountInfo,
        cached_at: now,
        expires_at: now + CACHE_DURATION,
      };
      this.error = null;
    },

    // 清除账户信息
    clearAccountInfo() {
      this.accountInfo = null;
      this.error = null;
    },

    // 设置加载状态
    setLoading(loading: boolean) {
      this.loading = loading;
    },

    // 设置错误信息
    setError(error: string) {
      this.error = error;
      this.loading = false;
    },

    // 获取账户信息（带缓存逻辑）
    async getAccountInfoWithCache(uniqueStr: string, forceRefresh = false): Promise<CachedAccountInfo | null> {
      // 如果有缓存且未过期，直接返回缓存数据
      if (!forceRefresh && this.accountInfo && !this.isCacheExpired) {
        console.log(`账户信息缓存命中，剩余时间: ${this.getCacheRemainingTime}秒`);
        return this.accountInfo;
      }

      // 缓存过期或强制刷新，重新获取数据
      return await this.fetchAccountInfo(uniqueStr);
    },

    // 获取账户信息
    async fetchAccountInfo(uniqueStr: string): Promise<CachedAccountInfo | null> {
      if (!uniqueStr) {
        this.setError('用户标识不能为空');
        return null;
      }

      this.setLoading(true);
      this.setError(null);

      try {
        console.log('正在获取账户信息:', uniqueStr);
        const response = await fetchAccountInfo(uniqueStr);
        
        this.setAccountInfo(response.data);
        console.log('账户信息获取成功:', response.data);
        
        return this.accountInfo;
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '获取账户信息失败';
        this.setError(errorMessage);
        console.error('获取账户信息失败:', error);
        return null;
      } finally {
        this.setLoading(false);
      }
    },

    // 刷新账户信息
    async refreshAccountInfo(uniqueStr: string): Promise<CachedAccountInfo | null> {
      return await this.getAccountInfoWithCache(uniqueStr, true);
    },
  },
});

// Need to be used outside the setup
export function useAccount() {
  return useAccountStore(store);
}